package com.fingard.dsp.bank.helpers;

import com.fingard.constant.Format;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

/**
 * 银保通通用方法工具类
 * 
 * @author Cruise
 * @date 2018/10/18
 */
public class YBTHelper {
    private static final Object staticLockObj = new Object();

	/**
	 * 获取批次序号
	 * 
	 * @param tmpReqDir 当前目录
	 * @param length 固定长度位数
	 * @return 实际批次序号
	 */
	public static String getBatSeqNo(String tmpReqDir, int length) {
        synchronized (staticLockObj) {
            int batSeqNo = 0;
            File tmpFileDir = new File(tmpReqDir);
            if (tmpFileDir.exists()) {
                File[] tmpFileList = tmpFileDir.listFiles();
                if (tmpFileList != null) {
                    batSeqNo = tmpFileList.length + 1;
                } else {
                    batSeqNo = 1;
                }
            } else {
                batSeqNo = 1;
            }
            return String.format("%0" + length + "d", batSeqNo);
        }
	}
	
	/**
	 * 获取服务器日切日期时间(银保通专用)
	 * 
	 * @param tmpReqDate 当前请求日期
	 * @return 日切判断后实际日期
	 */
	public static Date getDateCutTime(Date tmpReqDate, String dayCutTime) {
		Date tmpDateNow = new Date();
		
		// 读取本地渠道配置文件节点: <dayCutTime readme="银保通服务器日切时间(格式:HH:mm,例如:19:30),现场根据需要进行相应调整">20:30</dayCutTime>
		if (StringHelper.hasAnyChar(dayCutTime)) {
			Calendar now = Calendar.getInstance();
			now.setTime(tmpReqDate);
			String tmpDateTime = String.format("%02d", now.get(Calendar.HOUR_OF_DAY)) + String.format("%02d", now.get(Calendar.MINUTE));
			String tmpDayCutTime = dayCutTime.replace(":", "");
			if (Integer.parseInt(tmpDateTime) > Integer.parseInt(tmpDayCutTime)) {
				now.add(Calendar.DATE, 1);
				tmpDateNow = now.getTime();
			} else {
				tmpDateNow = tmpReqDate;
			}
		} else {
			tmpDateNow = tmpReqDate;
		}
		return tmpDateNow;
	}

	public static String dateParamFormat(String str, Date date) {
	    String tmpDate = Format.Date8Format.format(date);
	    String tmpYear = tmpDate.substring(0,4);
	    String tmpMonth = tmpDate.substring(4,6);
	    String tmpDay = tmpDate.substring(6,8);
        str = str.replace("{$YYYY}", tmpYear).replace("{$MM}", tmpMonth).replace("{$DD}", tmpDay);
        return  str;
    }
}
